/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.hathor.childcreator;

import com.hathor.conf.PropertyLoader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URISyntaxException;
import java.net.URLDecoder;
import java.util.Enumeration;
import java.util.Properties;
import java.util.jar.JarEntry;
import java.util.jar.JarInputStream;
import java.util.jar.JarOutputStream;
import org.apache.commons.io.FileUtils;

/**
 *
 * @author Kenneth
 */
public class ChildCreator {

    private Properties originalProperties;
    private FileOutputStream out;
    private File thisJarPath;
    private File copiedJar;
    private File originalJar;
    private File manifestFile;

    public void makeChild() {
        try {
            copySelf();
            getUnJarredProperties();
            editCopiedProperties();
            reJar();
        } catch (Exception e) {
            e.printStackTrace();
        }
        new File(copiedJar.getParent() + "/unJarred/").delete();
    }

    private void copySelf() throws URISyntaxException, IOException {
        String path = ChildCreator.class.getProtectionDomain().getCodeSource().getLocation().getPath();
        String decodedPath = URLDecoder.decode(path, "UTF-8");
        originalJar = //new File("C:\\Users\\Kenneth\\Documents\\NetBeansProjects\\relims-seeder\\target\\Hathor-1.0.jar");
                new File(decodedPath);
        copiedJar = new File(originalJar.getAbsolutePath().replace(".jar", "-reciever.jar"));
        FileUtils.copyFile(originalJar, copiedJar, true);
    }

    private void editCopiedProperties() {

        try {
            File defaultChildProperties = getUnJarredProperties();
            OutputStream out = new FileOutputStream(defaultChildProperties);
            Properties childProperties = new Properties();
            childProperties.setProperty("mothership.port", "" + PropertyLoader.getMotherShipPort());
            childProperties.store(out, "");
            out.close();
        } catch (Exception e) {
        } finally {
        }
    }

    private void editManifest() throws IOException {
        manifestFile.delete();
        createNewManifest(manifestFile);
    }

    private File getUnJarredProperties() throws IOException {
        JarInputStream in = null;
        OutputStream out = null;
        File propertiesFile = null;
        File f = new File(copiedJar.getParent() + "/unJarred/reciever.txt");
        f.mkdir();
        java.util.jar.JarFile jar = new java.util.jar.JarFile(copiedJar);
        Enumeration jarEntries = jar.entries();
        while (jarEntries.hasMoreElements()) {
            JarEntry file = (java.util.jar.JarEntry) jarEntries.nextElement();
            f = new File(copiedJar.getParent() + "/unJarred/" + file.getName());
            if (file.isDirectory()) { // if its a directory, create it
                f.mkdir();
                continue;
            }
            if (f.getAbsolutePath().contains("MANIFEST.MF")) {
                manifestFile = f.getAbsoluteFile();
            } else {
                java.io.InputStream is = jar.getInputStream(file); // get the input stream
                java.io.FileOutputStream fos = new java.io.FileOutputStream(new File(f.getAbsolutePath()));
                while (is.available() > 0) {  // write contents of 'is' to 'fos'
                    fos.write(is.read());
                }
                fos.close();
                is.close();
            }
        }
        propertiesFile = new File(copiedJar.getParent() + "/unJarred/default.properties");
        return propertiesFile;
    }

    private void reJar() throws FileNotFoundException, IOException {
        String path = copiedJar.getAbsolutePath();
        copiedJar.delete();
        FileOutputStream fos = new FileOutputStream(path);
        JarOutputStream jarout = new JarOutputStream(fos);
        File[] toBeJared = new File(copiedJar.getParent() + "/unJarred/").listFiles();
        for (File aFile : toBeJared) {
            jarout.putNextEntry(new JarEntry(aFile.getAbsolutePath()));
            FileInputStream in = new FileInputStream(aFile);
            while (true) {
                int nRead = in.read();
                if (nRead <= 0) {
                    break;
                }
                out.write(nRead);
                in.close();
            }
        }
        jarout.close();
    }

    private void createNewManifest(File targetMF) throws IOException {
        FileWriter writer = new FileWriter(targetMF);
        writer.write("Manifest-Version: 1.0" + System.lineSeparator());
        writer.write("Archiver-Version: Plexus Archiver" + System.lineSeparator());
        writer.flush();
        writer.write("Created-By: Apache Maven" + System.lineSeparator());
        writer.flush();
        writer.write("Built-By: Kenneth" + System.lineSeparator());
        writer.flush();
        writer.write("Build-Jdk: 1.7.0_09" + System.lineSeparator());
        writer.flush();
        writer.write("Main-Class: com.hathor.networking.BatchReciever" + System.lineSeparator());
        writer.flush();
        writer.write("Class-Path: log4j-1.2.16.jar com.springsource.org.apache.commons.io-1.4.0.jar" + System.lineSeparator());
        writer.flush();
        writer.close();
    }
}
